package com.gzdh.dishrecognition.ui.activity;

import static com.dhkj.web.utils.DataUtils.type;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.airbnb.lottie.LottieAnimationView;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.iot.bpaas.api.BPaaSApi;
import com.alipay.iot.bpaas.api.BPaaSInitCallback;
import com.alipay.iot.bpaas.api.InnerApi;
import com.alipay.iot.bpaas.api.ipc.IpcChannel;
import com.alipay.iot.bpaas.api.ipc.IpcListener;
import com.alipay.iot.bpaas.api.service.BPaaSCallback;
import com.alipay.iot.bpaas.api.service.BPaaSResponse;
import com.alipay.iot.sdk.APIManager;
import com.alipay.iot.sdk.InitFinishCallback;
import com.dhkj.web.basic.Constans;
import com.dhkj.web.bean.MacMainpSbruanDinner;
import com.dhkj.web.systemcenter.SysCenterRequestUtils;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.MyObserverUZip;
import com.dhkj.web.utils.RequestUtils;
import com.greendao.dao.BQEntityDao;
import com.greendao.dao.BmcmEntityDao;
import com.greendao.dao.BmzlEntityDao;
import com.greendao.dao.KSEntityDao;
import com.greendao.dao.MacMainpFoodMenuEntityDao;
import com.greendao.dao.MacMainpSbruanDinnerEntityDao;
import com.greendao.dao.WeekMenuBakEntityDao;
import com.gzdh.dishrecognition.AppContext;
import com.gzdh.dishrecognition.MainActivity;
import com.gzdh.dishrecognition.R;
import com.gzdh.dishrecognition.config.MyBaseConfig;
import com.gzdh.dishrecognition.config.SysConstConfig;
import com.gzdh.dishrecognition.config.SystemConfig;
import com.gzdh.dishrecognition.entity.BQEntity;
import com.gzdh.dishrecognition.entity.BmcmEntity;
import com.gzdh.dishrecognition.entity.BmzlEntity;
import com.gzdh.dishrecognition.entity.KSEntity;
import com.gzdh.dishrecognition.entity.MacMainpFoodMenuEntity;
import com.gzdh.dishrecognition.entity.MacMainpSbruanDinnerEntity;
import com.gzdh.dishrecognition.entity.WeekMenuBakEntity;
import com.gzdh.dishrecognition.thead.TimeThread;
import com.gzdh.dishrecognition.util.SystemUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class SplashScreen extends AppCompatActivity {
    private static final String TAG = "SplashScreen";

    TextView appname;
    LottieAnimationView lottie;

    private Context mContext;

    private BmcmEntityDao bmcmEntityDao;

    private WeekMenuBakEntityDao weekMenuBakEntityDao;

    private BmzlEntityDao bmzlEntityDao;

    private BQEntityDao bqEntityDao;

    private KSEntityDao ksEntityDao;

    private MacMainpSbruanDinnerEntityDao macMainpSbruanDinnerEntityDao;

    private MacMainpFoodMenuEntityDao macMainpFoodMenuEntityDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        mContext = this;
        bmcmEntityDao = AppContext.getInstance().getDaoSession().getBmcmEntityDao();
        weekMenuBakEntityDao = AppContext.getInstance().getDaoSession().getWeekMenuBakEntityDao();
        bmzlEntityDao = AppContext.getInstance().getDaoSession().getBmzlEntityDao();
        bqEntityDao = AppContext.getInstance().getDaoSession().getBQEntityDao();
        ksEntityDao = AppContext.getInstance().getDaoSession().getKSEntityDao();
        macMainpSbruanDinnerEntityDao = AppContext.getInstance().getDaoSession().getMacMainpSbruanDinnerEntityDao();
        macMainpFoodMenuEntityDao = AppContext.getInstance().getDaoSession().getMacMainpFoodMenuEntityDao();
        new TimeThread(this, null).start();
        lottie = findViewById(R.id.lottie);
        SharedPreferences sysCost = getSharedPreferences("sysCost", MODE_PRIVATE);
        SharedPreferences systemI = getSharedPreferences("systemI", MODE_PRIVATE);
        String sysApi = sysCost.getString("api", null);//读取username


        try {
            MyBaseConfig.initConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }

        String user = systemI.getString("user", "");
        if (sysApi == null) {
            //跳转去绑定页面进行绑定机器
            BindActivity.startAct(mContext);
            finish();
            return;
        } else {


//            Constans.getInstance().BaseUrl = "http://172.25.0.102:7901";
            Constans.getInstance().BaseUrl = sysApi;
            //设备签到
            RequestUtils.deviceSign(mContext, SystemUtils.getSerialNumber(), new MyObserverRes<String>(mContext, false) {
                @Override
                public void onSuccess(String result) {
                    String pos = result == null ? "" : result.replace("号机", "");
                    SysConstConfig.getInstance().setPos(pos);
                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {
                    Log.e("SplashScreen", errorMsg);
                }
            });
            //获取设备基本信息
            RequestUtils.getBaseSysInfo(mContext, user, SystemUtils.getSerialNumber(), new MyObserverUZip<JSONObject>(mContext, type(JSONObject.class), false) {
                @Override
                public void onSuccess(JSONObject result) {
                    System.out.println(result.toJSONString());
                    List<BmcmEntity> bmcmEntityList = result.getJSONArray("bmcm").toJavaList(BmcmEntity.class);
                    bmcmEntityDao.deleteAll();
                    bmcmEntityDao.insertInTx(bmcmEntityList);


                    JSONArray bmzlJsonArray = result.getJSONArray("bmzl");

                    List<BmzlEntity> bmzlEntityList = new ArrayList<>();
                    for (int i = 0; i < bmzlJsonArray.size(); i++) {
                        BmzlEntity bmzlEntity = new BmzlEntity();
                        bmzlEntity.setBm(bmzlJsonArray.getJSONObject(i).getString("bm").trim());
                        bmzlEntity.setName(bmzlJsonArray.getJSONObject(i).getString("name"));
                        bmzlEntityList.add(bmzlEntity);
                    }
                    bmzlEntityDao.deleteAll();
                    bmzlEntityDao.insertInTx(bmzlEntityList);

                    JSONArray bqArray = result.getJSONArray("bq");
                    if(bqArray != null) {
                        List<BQEntity> bqList = bqArray.toJavaList(BQEntity.class);
                        bqEntityDao.deleteAll();
                        bqEntityDao.insertInTx(bqList);
                    }

                    JSONArray ksArray = result.getJSONArray("ks");
                    if(ksArray != null) {
                        List<KSEntity> ksList = ksArray.toJavaList(KSEntity.class);
                        ksEntityDao.deleteAll();
                        ksEntityDao.insertInTx(ksList);
                    }

                    try {
                        List<WeekMenuBakEntity> weekMenuBakEntityList = result.getJSONArray("weekMenuBak").toJavaList(WeekMenuBakEntity.class);
                        if (weekMenuBakEntityList.size() > 0) {
                            weekMenuBakEntityDao.deleteAll();
                            weekMenuBakEntityDao.insertInTx(weekMenuBakEntityList);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {

                        List<MacMainpSbruanDinner> macMainpSbruanDinnerList = result.getJSONArray("macMainpSbruanDinnerList").toJavaList(MacMainpSbruanDinner.class);
                        macMainpSbruanDinnerEntityDao.deleteAll();
                        if (macMainpSbruanDinnerList.size() > 0) {
                            List<MacMainpSbruanDinnerEntity> macMainpSbruanDinnerEntities = new ArrayList<>();
                            for (MacMainpSbruanDinner goo : macMainpSbruanDinnerList) {
                                MacMainpSbruanDinnerEntity macMainpSbruanDinnerEntity = new MacMainpSbruanDinnerEntity();
                                macMainpSbruanDinnerEntity.setDinner(goo.getDinner());
                                macMainpSbruanDinnerEntity.setStartTime(goo.getStartTime());
                                macMainpSbruanDinnerEntity.setEndTime(goo.getEndTime());
                                macMainpSbruanDinnerEntity.setDeviceId(goo.getDeviceId());
                                macMainpSbruanDinnerEntity.setId(goo.getId());
                                macMainpSbruanDinnerEntities.add(macMainpSbruanDinnerEntity);
                            }
                            macMainpSbruanDinnerEntityDao.insertInTx(macMainpSbruanDinnerEntities);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                    try {

                        List<MacMainpFoodMenuEntity> macMainpFoodMenuList = result.getJSONArray("macMainpFoodMenuList").toJavaList(MacMainpFoodMenuEntity.class);
                        macMainpFoodMenuEntityDao.deleteAll();
                        if (macMainpFoodMenuList.size() > 0) {
                            List<MacMainpFoodMenuEntity> macMainpFoodMenuEntities = new ArrayList<>();
                            for (MacMainpFoodMenuEntity goo : macMainpFoodMenuList) {
                                MacMainpFoodMenuEntity macMainpFoodMenuEntity = new MacMainpFoodMenuEntity();
                                macMainpFoodMenuEntity.setId(goo.getId());
                                macMainpFoodMenuEntity.setName(goo.getName());
                                macMainpFoodMenuEntity.setPrice(goo.getPrice());
                                macMainpFoodMenuEntity.setCardid(goo.getCardid());
                                macMainpFoodMenuEntity.setZl(goo.getZl());
                                macMainpFoodMenuEntity.setCode(goo.getCode());
                                macMainpFoodMenuEntities.add(macMainpFoodMenuEntity);
                            }
                            macMainpFoodMenuEntityDao.insertInTx(macMainpFoodMenuEntities);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {

                }
            });
        }


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                SysCenterRequestUtils.init(getApplicationContext(), SystemUtils.getSerialNumber(), new MyObserverRes<JSONObject>(getApplicationContext(), false) {
                    @Override
                    public void onSuccess(JSONObject result) {
                        JSONObject shopMachineJson = result.getJSONObject("shopMachine");
                        JSONObject deviceJson = result.getJSONObject("device");
                        if (shopMachineJson == null || shopMachineJson.isEmpty()) {
                        } else {
                            SharedPreferences userInfo = getSharedPreferences("sysCost", MODE_PRIVATE);
                            SharedPreferences.Editor editor = userInfo.edit();
                            editor.putString("api", shopMachineJson.getString("businessUrl"));
                            editor.putInt("type", new BigDecimal(deviceJson.getString("type")).intValue());
                            SysConstConfig.getInstance().setDeviceType(new BigDecimal(deviceJson.getString("type")).intValue());
                            editor.putString("merchantName", shopMachineJson.getString("merchantName"));
                            editor.commit();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {

                    }
                });
                SharedPreferences sharedPreferences = getSharedPreferences("systemI", Context.MODE_PRIVATE); //私有数据
                String user = sharedPreferences.getString("user", "");
                if (SysConstConfig.getInstance().getDeviceType() == 2 || SysConstConfig.getInstance().getDeviceType() == 3) {
                    //支付宝组件，需要启动支付宝初始化
                    System.out.println("支付宝初始化");
                    init();
                }
                if ("".equals(user) || !SysConstConfig.getInstance().isAutoLogin()) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                    finish();
                    return;
                }
                startActivity(new Intent(mContext, MainActivity.class));
                finish();
            }
        }, 5000);
        //检查权限
        if (!Settings.canDrawOverlays(mContext)) {
            //启动Activity让用户授权
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            startActivity(intent);
//            return;
        }
//        try {
//
//            System.out.println("成功" + Test_lib.getStrA("B6EBE557"));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }

    private void init() {
        Log.i(TAG, "init");
        try {
            // 如果iot初始化成功
            if (APIManager.getInstance().getDeviceAPI().getDeviceSn() != null) {
                initABCP();
                return;
            }
            //iot sdk初始化成功后，再初始化SDK
            APIManager.getInstance().initialize(getApplicationContext(), SystemConfig.getInstance().getAbcpApplicationAppid(), new InitFinishCallback() {
                @Override
                public void initFinished(boolean success) {
                    Log.d(TAG, "iot sdk init success = " + success);
                    if (success) {
                        initABCP();
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "APIManager initialize error", e);
        }
    }


    /**
     * bpaas api初始化  传入在BPaas平台上申请到的Appid、应用版本号信息
     */
    public void initABCP() {
        //模板应用appid_c1
        Bundle extInfo = new Bundle();
        extInfo.putString("ext_tpl_app_id", SystemConfig.getInstance().getTemplateId());
        extInfo.putInt("ext_tpl_display_mode", 1);
        extInfo.putBoolean("isFloat", true);
        //bpaas api初始化  传入在BPaas平台上申请到的Appid、应用版本号信息
        BPaaSApi.getInstance().init(getApplicationContext(), SystemConfig.getInstance().getAbcpApplicationAppid(), extInfo, new BPaaSInitCallback() {
            @Override
            public void onSuccess() {
                Log.i(TAG, "init ABCP success");
                clickInit(null);
                InnerApi.addIpcListener(mIpcListener);
            }

            @Override
            public void onFail(String msg) {
                Log.e(TAG, "init ABCP fail reason:" + msg);
            }
        });
    }

    private IpcListener mIpcListener = new IpcListener() {
        @Override
        public void onConnected(IpcChannel ipcChannel) {
            Log.i(TAG, "onConnected");
            init();
        }

        @Override
        public void onDisconnected(IpcChannel ipcChannel) {
            Log.i(TAG, "onDisconnected");
        }

        @Override
        public void onConnectionFailed(IpcChannel ipcChannel) {
            Log.i(TAG, "onConnectionFailed");
        }
    };

    // 团餐模板初始化
    public void clickInit(View view) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("logicGroupID", "BUSINESS_2291311712665600");
        jsonObject.put("industryBizType", "business");
        jsonObject.put("partnerId", "2088121760636121");
        jsonObject.put("merchantId", "2088441828867338");
        jsonObject.put("merchantName", "广州市鼎鸿电子科技有限公司");
        jsonObject.put("isvName", "广州市鼎鸿电子科技有限公司");
        jsonObject.put("useOfflinePay", true);
        jsonObject.put("uploadTimeOutSecs", 15); // 等待结果页支付查询超时时间，默认30s


        Bundle bundle = new Bundle();
        bundle.putString("templateId", SystemConfig.getInstance().getTemplateId());
        bundle.putString("operateType", "init");
        bundle.putString("page", "canteen");
        bundle.putString("templateParams", jsonObject.toJSONString());
        BPaaSApi.getInstance().startBPaaSService(SystemConfig.getInstance().getAbcpApplicationAppid(), SystemConfig.getInstance().getTemplateServiceCode(), bundle, new BPaaSCallback() {
            @Override
            public void onResponse(BPaaSResponse response) {
//                        responseInvoke(response, "canteen init");
            }

            @Override
            public void onEvent(String eventId, String data, Bundle extra) {
                Log.i(TAG, "onEvent eventId:" + eventId + ",data:" + data);
            }
        });
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //页面退出时移除IpcListener，避免内存泄露
        InnerApi.removeIpcListener(mIpcListener);
    }
}
